package com.fengmi.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.fengmi.dto.GoodDTO;
import com.fengmi.dto.PageDTO;
import com.fengmi.dto.ProductDTO;
import com.fengmi.entity.MallGoods;
import com.fengmi.entity.MallGoodsSku;
import com.fengmi.entity.SysUser;
import com.fengmi.mapper.GoodsMapper;
import com.fengmi.service.IGoodsService;
import com.fengmi.vo.PageResultVO;
import com.fengmi.vo.ResultVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 作者：陈学虎
 * 时间：2021/7/11 0011 下午 7:35
 */
@Service
@Transactional
public class GoodsService implements IGoodsService {

    @Autowired
    private GoodsMapper goodsMapper;


    @Override
    public PageResultVO<MallGoods> findGoods(PageDTO<ProductDTO> pageDTO) {
        if (ObjectUtil.isEmpty(pageDTO)){
            return new PageResultVO<>(false,"请求参数错误");
        }

        PageHelper.startPage(pageDTO.getPage(),pageDTO.getSize());
        List<MallGoods> goods = goodsMapper.findGoods(pageDTO.getWhere());
        PageInfo<MallGoods> pageInfo = new PageInfo<>(goods);

        PageResultVO<MallGoods> pageResultVO = new PageResultVO<>(true,"查询成功");
        pageResultVO.setData(pageInfo.getList());
        pageResultVO.setTotal(pageInfo.getTotal());
        pageResultVO.setPages(pageInfo.getPages());
        return pageResultVO;
    }

    @Override
    public ResultVO changeGoodStatus(MallGoods mallGoods) {
        if (ObjectUtil.isEmpty(mallGoods)){
            return new ResultVO(false,"请求参数错误");
        }

        int i = goodsMapper.changeGoodStatus(mallGoods);

        return new ResultVO(i==1?true:false,i==1?"修改成功":"修改失败");
    }

    @Override
    public ResultVO save(GoodDTO goodDTO) {
        if (goodDTO == null || goodDTO.getGoods() == null || goodDTO.getSkus() == null){
            return new ResultVO(false,"请求参数错误");
        }
        SysUser principal = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(principal.getUserId());

        MallGoods goods = goodDTO.getGoods();
     //补全spu
        goods.setCreateTime(new Date());
        goods.setUpdateTime(new Date());
        goods.setAuditStatus(0+"");
        goods.setIsDelete(0+"");
        //先保存spu
        goodsMapper.saveSpu(goodDTO.getGoods());
        //清除sku
        goodsMapper.delBySupId(goods.getSpuId()+"");

        goodDTO.getSkus().forEach(sku -> {
            //补全sku
            sku.setCreateTime(new Date());
            sku.setUpdateTime(new Date());
            sku.setSpuId(goods.getSpuId());
            goodsMapper.saveSku(sku);
        });


        return new ResultVO(true,"保存成功");
    }


}
